package configdto

import (
	"gitee.com/ichub/goconfig/common/base/basedto"
	"gitee.com/ichub/goconfig/common/base/encrypt"
	"github.com/duke-git/lancet/system"
	"github.com/gookit/goutil/strutil"
	"os"
	"strings"
)

/*
	@Title    文件名称: config_item.go
	@Description  描述: 配置项解析值

	@Author  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
	@Update  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
*/

const ITEM_KEY = "ITEM_KEY"

type ConfigItem struct {
	//键值
	Key string `json:"key"`
	//配置值
	Value string `json:"value"`
	// 环境变量
	EnvValue string `json:"env_value"`
	// 默认值
	DefaultValue string `json:"default_value"`
	// 实际值
	EndValue string `json:"end_value"`

	basedto.BaseEntity
}

func NewConfigItem(k, v string) *ConfigItem {
	var cfgItem = &ConfigItem{
		Key:   k,
		Value: v,
	}
	cfgItem.InitProxy(cfgItem)
	return cfgItem
}

func (this *ConfigItem) Check() bool {
	var has = strutil.HasPrefix(this.Value, "${")
	if !has {
		return true
	}
	return strutil.HasSuffix(this.Value, "}")
}

// ${HOSTURL:huawei.akunlong.top:2379}
func (this *ConfigItem) ParseValue() *ConfigItem {
	if strings.Contains(this.Value, "${") {
		this.parseEndValue()
	} else {
		this.defaultValue()
		this.Decrypt()
	}
	return this
}

func (this *ConfigItem) parseEndValue() *ConfigItem {
	var strs = strings.Split(this.Value, ":")

	this.EnvValue = strings.Split(strs[0], "{")[1]

	var start = strings.Index(this.Value, ":") + 1
	var end = len(this.Value) - 1

	this.DefaultValue = this.Value[start:end]

	if system.GetOsEnv(this.EnvValue) != "" {
		this.EndValue = os.Getenv(this.EnvValue)
	} else {
		this.EndValue = this.DefaultValue
	}

	this.Decrypt()
	return this

}
func (this *ConfigItem) defaultValue() *ConfigItem {
	this.EnvValue = ""
	this.DefaultValue = this.Value
	this.EndValue = this.Value
	return this
}

// decrypt
func (this *ConfigItem) IfEnc() bool {

	return strings.Contains(this.EndValue, "enc(")
}

// decrypt
func (this *ConfigItem) Decrypt() string {
	if this.IfEnc() {
		var eval = this.EndValue
		eval = strings.TrimSpace(eval)
		eval = strings.Trim(eval, "enc(")
		eval = strings.Trim(eval, ")")
		eval = Context.Encdec().DecBase64(eval)
		this.EndValue = eval
	}
	return this.EndValue
}

func (this *ConfigItem) Encrypt() string {
	var eval = this.EndValue
	eval = encrypt.EncDecInst.EncBase64(eval)
	this.EndValue = eval
	return eval

}
